// 请求用 JS
import { api_root } from './config.js';
var readTimerId = '';
var readNum = '';
const http = {
	// 请求方法统一
	request(param){
		// if(!param.data) param.data = {}
		return new Promise((resolve, reject) => {
			http.sendRequest({
				url: param.url,
				method: param.method,
				data: param.data || {},
				success: res => {
					resolve(res.data);
				}
			},
			uni.getStorageSync('token'))
		})
	},
	// 拦截器
	sendRequest(s, token) {
		let that = this;
		uni.request({
			url: api_root + s.url,
			header: s.header || {
				"content-type": "application/json;charset=utf-8",
				// "Authorization": 'Bearer ' +  token,
				"Authorization": token,
				"Access-Control-Allow-Origin": "*"
			},
			timeout: 5000,
			data: s.data || {},
			method: s.method || "GET",
			dataType: s.dataType || "json",
			success: (res) => {
				if (res.data.code == 401) {
					// 登录态失效, 重新登录
					uni.removeStorageSync('token');
					uni.removeStorageSync('identify');
					const pages = getCurrentPages()
					if(pages[pages.length - 1].route != 'pages/login'){
						that.doLogin();
					}
					return;
				} else if (res.data.code == 200) {
					//对空值进行过滤，返回空字符串
					if(res.data.data){
						for (var key in res.data.data) {
							if (res.data.data[key] == null) {
								res.data.data[key]="";
							}else if(typeof(res.data.data[key])!=null && typeof(res.data.data[key])=="object"){
								for (var key2 in res.data.data[key]) {
									if (res.data.data[key][key2] == null ) {
										res.data.data[key][key2]="";
									}
								}
	
								if(res.data.data[key].length>0){
									for (var i=0;i<res.data.data[key].length;i++) {
										for (var key3 in res.data.data[key][i]) {
											if (res.data.data[key][i][key3] == null) {
												res.data.data[key][i][key3]="";
											}
										}
									}
								}
							}
						}
					}
					s.success && s.success(res.data);
				} else {
					if(res.data.message){
						that.showToast('none',res.data.message);
						s.fail && s.fail(res.data);
					}else{
						that.showToast('error','数据错误');
					}
					return false;
				}
			},
			fail: (err) => {
				that.showToast('none',err);
			},
			complete(err) {
				s.complete && s.complete(err.message);
			}
		})
	},
	doLogin(e) {
		console.log('登录态失效，去登录');
		uni.hideLoading();

		// 获取进入页的地址及参数
		let curPage = getCurrentPages();
		let route = curPage[curPage.length - 1].route; //获取当前页面的路由
		let params = curPage[curPage.length - 1].options; //获取当前页面参数，如果有则返回参数的对象，没有参数返回空对象{}
		let query = '';
		let keys = Object.keys(params); //获取对象的key 返回对象key的数组
		if (keys.length > 0) {
			query = keys.reduce((pre, cur) => {
				return pre + cur + '=' + params[cur] + '&';
			}, '?').slice(0, -1);
		}
		uni.reLaunch({ url: "/pages/login" });
	},
}
export default http;